<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>查询学生申请记录</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f0f4f8;
            margin: 0;
            padding: 0;
        }

        header {
            background-color: #005f99;
            color: white;
            padding: 20px;
            text-align: center;
        }

        .results-container {
            margin: 20px auto;
            padding: 20px;
            background-color: white;
            max-width: 1000px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        table {
            width: 100%;
            border-collapse: collapse;
            table-layout: auto;
        }

        table th, table td {
            padding: 10px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        table th {
            background-color: #e7f3ff;
            min-width: 120px;
        }

        .status {
            padding: 5px 10px;
            border-radius: 5px;
            color: white;
            font-weight: bold;
        }

        .status.pending {
            background-color: #ffa500;
        }

        .status.accepted {
            background-color: #4caf50;
        }

        .status.rejected {
            background-color: #f44336;
        }

        .action-buttons button {
            padding: 5px 10px;
            background-color: #005f99;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin-right: 5px;
        }

        .action-buttons button:hover {
            background-color: #004d80;
        }

        .pagination {
            text-align: center;
            margin-top: 20px;
        }

        .pagination button {
            padding: 10px 20px;
            margin: 0 5px;
            cursor: pointer;
            background-color: #005f99;
            color: white;
            border: none;
            border-radius: 5px;
        }

        .pagination button:disabled {
            background-color: #ddd;
            cursor: not-allowed;
        }

        .pagination button:hover:not(:disabled) {
            background-color: #004d80;
        }

        .scrollable-text {
            max-width: 200px;
            height: 50px;
            overflow-y: auto;
            padding: 5px;
        }

        /* 毛玻璃效果 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
            backdrop-filter: blur(10px); /* 毛玻璃效果 */
            z-index: 1000;
        }

        .modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            max-width: 80%;
            max-height: 80%;
            overflow-y: auto;
        }

        .modal button {
            margin-top: 20px;
            padding: 10px 20px;
            background-color: #005f99;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        .modal button:hover {
            background-color: #004d80;
        }

        /* 美化“查看全文”按钮 */
        .view-full-btn {
            padding: 5px 12px;
            background-color: #007acc;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            margin-top: 5px;
            transition: all 0.3s ease;
        }

        .view-full-btn:hover {
            background-color: #005f99;
            transform: scale(1.1);
        }

        /* 手机端适配 */
        @media (max-width: 768px) {
            table th, table td {
                font-size: 12px;
                padding: 8px;
            }

            .pagination button {
                padding: 8px 16px;
            }
        }
    </style>
</head>
<body>

<header>
    <h1>查询学生申请记录</h1>
</header>

<section class="results-container">
    <h3>申请记录</h3>
    <table id="applications-table">
        <thead>
        <tr>
            <th>学生姓名</th>
            <th>导师姓名</th>
            <th>申请理由</th>
            <th>研究兴趣</th>
            <th>申请状态</th>
            <th>申请时间</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <!-- 查询结果将填充到这里 -->
        </tbody>
    </table>
    <div class="pagination">
        <button id="prev-page" disabled>上一页</button>
        <button id="next-page">下一页</button>
    </div>
</section>

<!-- Modal for viewing full application reason -->
<div class="modal" id="modal">
    <div class="modal-content">
        <h2>申请理由</h2>
        <p id="modal-text"></p>
        <button onclick="closeModal()">关闭</button>
    </div>
</div>

<script>
    let currentPage = 1;
    const pageSize = 5;
    let totalRecords = 0;

    // 获取申请记录
    async function fetchApplications(page = 1) {
        const url = `/api/v1/applications/list?pageNum=${page}&pageSize=${pageSize}`;

        try {
            const response = await fetch(url);
            const data = await response.json();

            if (data.code === 200) {
                totalRecords = data.data.total;
                renderApplications(data.data.records);
                updatePagination();
            } else {
                alert("查询失败！");
            }
        } catch (error) {
            console.error("请求错误", error);
            alert("网络错误，请稍后再试。");
        }
    }

    // 渲染申请记录
    function renderApplications(records) {
        const tbody = document.getElementById("applications-table").getElementsByTagName("tbody")[0];
        tbody.innerHTML = ''; // 清空现有内容

        if (records.length === 0) {
            tbody.innerHTML = '<tr><td colspan="7" style="text-align: center;">没有找到申请记录</td></tr>';
            return;
        }

        records.forEach(record => {
            const statusClass = getStatusClass(record.status);
            const statusText = getStatusText(record.status);
            const row = document.createElement("tr");
            row.setAttribute('data-id', record.id); // 添加 data-id 属性用于后续操作
            row.innerHTML = `
                    <td>${escapeHtml(record.studentName)}</td>
                    <td>${escapeHtml(record.mentorProfileName)}</td>
                    <td>
                        <div class="scrollable-text">${escapeHtml(record.applicationReason)}</div>
                        <button class="view-full-btn" data-text="${escapeAttribute(record.applicationReason)}">查看全文</button>
                    </td>
                    <td>${escapeHtml(record.researchInterests)}</td>
                    <td><span class="status ${statusClass}">${statusText}</span></td>
                    <td>${new Date(record.createdAt).toLocaleString()}</td>
                    <td class="action-buttons">
                        <button onclick="updateStatus(${record.id}, 'accepted')">同意</button>
                        <button onclick="updateStatus(${record.id}, 'rejected')">拒绝</button>
                    </td>
                `;
            tbody.appendChild(row);
        });

        // 添加“查看全文”按钮的事件监听器
        attachViewFullEventListeners();
    }

    // 获取状态的样式类
    function getStatusClass(status) {
        switch (status) {
            case 'pending': return 'pending';
            case 'accepted': return 'accepted';
            case 'rejected': return 'rejected';
            default: return '';
        }
    }

    // 获取状态文本
    function getStatusText(status) {
        switch (status) {
            case 'pending': return '待处理';
            case 'accepted': return '已同意';
            case 'rejected': return '已拒绝';
            default: return '';
        }
    }

    // 打开查看全文的 Modal
    function openModal(text) {
        document.getElementById("modal-text").innerText = text;
        document.getElementById("modal").style.display = "flex";
    }

    // 关闭 Modal
    function closeModal() {
        document.getElementById("modal").style.display = "none";
    }

    // 更新申请状态（优化后的版本）
    async function updateStatus(applicationId, action) {
        const row = document.querySelector(`#applications-table tbody tr[data-id="${applicationId}"]`);
        if (!row) {
            alert("未找到对应的申请记录。");
            return;
        }

        const statusCell = row.querySelector('td:nth-child(5) .status');
        const originalStatus = statusCell.innerText;
        const originalStatusClass = statusCell.className;

        // 立即更新前端状态
        const newStatusClass = getStatusClass(action);
        const newStatusText = getStatusText(action);
        statusCell.className = `status ${newStatusClass}`;
        statusCell.innerText = newStatusText;

        try {
            const formData = new FormData();
            formData.append('status', action);

            const response = await fetch(`/api/v1/applications/updateStatus/${applicationId}`, {
                method: 'PUT',
                body: formData
            });

            const result = await response.json();

            if (result.code !== 200) {
                throw new Error("操作失败");
            }

            // 操作成功，无需进一步处理
        } catch (error) {
            console.error("更新申请状态失败", error);
            // 回滚前端状态
            statusCell.className = originalStatusClass;
            statusCell.innerText = originalStatus;
            alert("操作失败，请重试！");
        }
    }

    // 更新分页按钮状态
    function updatePagination() {
        document.getElementById("prev-page").disabled = currentPage <= 1;
        document.getElementById("next-page").disabled = currentPage * pageSize >= totalRecords;
    }

    // 点击上一页和下一页按钮
    document.getElementById("prev-page").addEventListener("click", () => {
        if (currentPage > 1) {
            currentPage--;
            fetchApplications(currentPage);
        }
    });

    document.getElementById("next-page").addEventListener("click", () => {
        if (currentPage * pageSize < totalRecords) {
            currentPage++;
            fetchApplications(currentPage);
        }
    });

    // 初始加载
    fetchApplications(currentPage);

    // 附加“查看全文”按钮的事件监听器
    function attachViewFullEventListeners() {
        const buttons = document.querySelectorAll('.view-full-btn');
        buttons.forEach(button => {
            button.addEventListener('click', () => {
                const text = button.getAttribute('data-text');
                openModal(text);
            });
        });
    }

    // 辅助函数：转义HTML以防止XSS
    function escapeHtml(text) {
        const map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }

    // 辅助函数：转义属性值
    function escapeAttribute(text) {
        const map = {
            '&': '&amp;',
            '"': '&quot;',
            "'": '&#039;',
            '<': '&lt;',
            '>': '&gt;'
        };
        return text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }
</script>

</body>
</html>
